﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TookKit.Mvvm.Attributes;

namespace TookKit.Mvvm.Extensions
{
    /// <summary>
    /// 获取类型的构造器，返回参数最多的构造器
    /// </summary>
    public static class TypeExtension
    {
        /// <summary>
        /// 获取类型的DependencyInjection特性
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IEnumerable<DependencyInjectionAttribute> GetDependencyInjectionAttributes(this Type type) 
        { 
            var typeInfo = type.GetTypeInfo();
            return typeInfo.GetCustomAttributes<DependencyInjectionAttribute>();
        }


        /// <summary>
        /// 获取类型的构造器
        /// </summary>
        /// <param name="serviceType"></param>
        /// <param name="_intferfaceMaps"></param>
        /// <returns></returns>
        public static ConstructorInfo GetConstructorInfo(this Type serviceType, ConcurrentDictionary<Type, Type> _intferfaceMaps) 
        {
            Type t;
            if (_intferfaceMaps.ContainsKey(serviceType))
            {
                t = _intferfaceMaps[serviceType] ?? serviceType;
            }
            else
            {
                t = serviceType;
            }

            var constructorInfos = t.GetConstructors();//返回所有构造器

            return constructorInfos.OrderByDescending(c => c.GetParameters().Length).FirstOrDefault();
        }
    }
}
